package net.zui.action;

import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;

import net.zui.comp.ZBase;
import net.zui.comp.ZBaseFrame;
import net.zui.entity.ZBaseManager;
import net.zui.enume.ActionEnum;

public class WindowMouseAction extends ZMouseAction {

	private ZBaseManager manager;
	private ActionDispather action;
	private ZBase tmp;

	public WindowMouseAction(ZBaseFrame frame) {
		super(frame);
		manager=frame.getManager();
		action=frame.getActionDispather();
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		dispather(e,ActionEnum.mouseClicked,new MouseCallback() {
			@Override
			public void call(ZMouseAction mouseAction) {
				mouseAction.mouseClicked(e);
			}
		});
	}
	
	@Override
	public void mousePressed(MouseEvent e) {
		dispather(e,ActionEnum.mousePressed,new MouseCallback() {
			@Override
			public void call(ZMouseAction mouseAction) {
				mouseAction.mousePressed(e);
			}
		});
	}
	
	@Override
	public void mouseReleased(MouseEvent e) {
		tmp = dispather(e,ActionEnum.mouseReleased,new MouseCallback() {
			@Override
			public void call(ZMouseAction mouseAction) {
				mouseAction.mouseReleased(e);
			}
		});
		if(tmp!=null && tmp.hasFocus()) {
			manager.setFocus(tmp);
			tmp.setFocus();
		}else {
			manager.setFocus(null);
		}
	}
	
	@Override
	public void mouseWheelMoved(MouseWheelEvent e) {
		dispather(e,ActionEnum.mouseWheelMoved,new MouseCallback() {
			@Override
			public void call(ZMouseAction mouseAction) {
				mouseAction.mouseWheelMoved(e);
			}
		});
	}
	
	@Override
	public void mouseDragged(MouseEvent e) {
		dispather(e,ActionEnum.mouseDragge,new MouseCallback() {
			@Override
			public void call(ZMouseAction mouseAction) {
				mouseAction.mouseDragged(e);
			}
		});
	}
	
	@Override
	public void mouseMoved(MouseEvent e) {
		tmp = dispather(e,ActionEnum.mouseMove,new MouseCallback() {
			@Override
			public void call(ZMouseAction mouseAction) {
				mouseAction.mouseMoved(e);
			}
		});
		manager.setHover(tmp);
	}
	
	private ZBase dispather(MouseEvent e,ActionEnum enume,MouseCallback back) {
		tmp=manager.findByPointAble(e.getX(), e.getY());
		if(tmp!=null && tmp.getAble()) {
			e.setSource(tmp);
			boolean res=action.mouseEventFire(tmp.getId(), enume, e);
			if(!res) {
				ZMouseAction mouseAction = tmp.getOuterMouse();
				if(mouseAction!=null)back.call(mouseAction);
			}
			return tmp;
		}
		boolean res = action.mouseEventFire("this", enume, e);
		if(!res) {
			ZMouseAction mouseAction=frame.getOuterMouse();
			if(mouseAction!=null) {
				e.setSource(frame);
				back.call(mouseAction);
			}
		}
		return null;
	}
	
	static interface MouseCallback{
		void call(ZMouseAction mouseAction);
	}
}
